/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package app.net.client;

import app.net.Message;
import app.net.messages.IdMessage;
import app.net.messages.SimpleStringMessage;
import app.net.messages.SyncMessage;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * waits for sync from server
 *
 * @author skyr
 */
public class ClientReceiveThread implements Runnable {

    private ClientGameLoop clientGameLoop;
    private Socket socket;
    private boolean receiveRunning = true;
    private ObjectInputStream ois;
    private int id;

    public ClientReceiveThread(Socket socket, ClientGameLoop clientGameLoop) {
        this.socket = socket;
        this.clientGameLoop = clientGameLoop;
        try {
            ois = new ObjectInputStream(socket.getInputStream());
        } catch (IOException ex) {
            Logger.getLogger(ClientReceiveThread.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void run() {
        try {
            /*
             * receive id
             */
            IdMessage idMessage = (IdMessage) ois.readObject();
            id = idMessage.getId();
            clientGameLoop.setId(id);
            while (receiveRunning) {
                Message m = (Message) ois.readObject();
                /*
                 * read message and sync or reset according to message type 
                 */
                if (m instanceof SyncMessage) {
                    SyncMessage sm = (SyncMessage) m;
//                    System.out.println("receiving " + sm.getId() + " - " + sm.getX() + "," + sm.getY());
                    clientGameLoop.setSyncMessage(sm);
                }else if (m instanceof SimpleStringMessage){
                    SimpleStringMessage ssm = (SimpleStringMessage) m;
                    if (ssm.getS().equals("reset")){
                        clientGameLoop.resetSyncMap();
                    }
                }
            }
        } catch (Exception ex) {
            Logger.getLogger(ClientReceiveThread.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void start() {
        Thread t = new Thread(this);
        t.start();
    }

    public void stop() {
        receiveRunning = false;
    }
}
